package com.gwtintegration.smartrf.shared;

import java.util.Date;

public class RequestFactoryEncoder {

	private RequestFactoryEncoder() {}

	public static String getString(Object value) {
		if (value == null) {
			return null;
		}

		String className = value.getClass().getName();
		String stringValue = null;

		if (value instanceof String || value instanceof Integer || value instanceof Long || value instanceof Float || value instanceof Double) {
			stringValue = value.toString();
		} else if (value instanceof Date) {
			stringValue = Long.toHexString(((Date) value).getTime());
		} else {
			throw new IllegalArgumentException("The type " + className + " is not supported.");
		}

		return className + "|" + stringValue;
	}

	public static Object getObject(String value) {
		if (value == null || value.isEmpty()) {
			return null;
		}

		String[] values = value.split("|", 2);
		if (values == null || values.length != 2) {
			throw new IllegalArgumentException("The value '" + value + "' is not in the correct format.");
		}

		String className = values[0];
		String stringValue = values[1];

		if (String.class.getName().equals(className)) {
			return stringValue;
		} else if (Integer.class.getName().equals(className)) {
			return Integer.valueOf(stringValue);
		} else if (Long.class.getName().equals(className)) {
			return Long.valueOf(stringValue);
		} else if (Float.class.getName().equals(className)) {
			return Float.valueOf(stringValue);
		} else if (Double.class.getName().equals(className)) {
			return Double.valueOf(stringValue);
		} else if (Date.class.getName().equals(className)) {
			return new Date(Long.valueOf(stringValue, 16));
		} else {
			throw new IllegalArgumentException("The type " + className + " is not supported.");
		}
	}
}
